<?php
/**
 * 视频管理
 * @author Jimmy
 * @date 2015-09-23 16:08:11
 */
namespace Admin\Controller;
use Admin\Model\VideoAttrModel;
use Think\Model\ViewModel;
use Think\Page;

class VideoController extends CommonController {

    /**
     * 首页  加载list列表数据
     */
    function index() {
        //列表过滤器，生成查询Map对象
        $map = array();

        $model = D (CONTROLLER_NAME);
        if (! empty ( $model )) {
            $map['lan']=LANG_SET;
            $title = LANG_SET == 'zh-cn'?'title_cn':'title_en';
            $field = 'id,category_id,creator,created_at,'.$title;

            $model = $model->field($field)->where($map)->order('created_at desc')->select();
            $this->assign ( 'lists', $model );
        }
        $video_role =  getSiginRoleName() == 'customer'? 'hidden':'';
        $this->assign('video_role',$video_role);
        $this->display ();
        return;
    }

    /**
     * ajax 获取编辑页面数据
     */
    public function edit() {

        $model = D ( CONTROLLER_NAME );
        $attr_model = new VideoAttrModel();

        $id = $_REQUEST [$model->getPk ()];
        $vo = $model->getById ( $id );
        $vo['tag'] = $attr_model->getAttrByVideoId($id,1);
        $vo['people'] = $attr_model->getAttrByVideoId($id,2);

        echo json_encode($vo);
    }

    /**
     *   主要对于网格布局的数据进行分页处理 和搜索、筛选功能
     *
     */
    public function _before_index() {
        $map = array();
        $view = isset($_SESSION['video_view'])?$_SESSION['video_view'] : 'video-grid';
        $model = new ViewModel();
        $attribute = D('video_attr');
        //根据当前的语言筛选 播放的视频
        $map['lan']=LANG_SET;

        $title = LANG_SET == 'zh-cn'?'title_cn':'title_en';
        $field = 'youku_url,youtube_url,video_thumbnail,id,'.$title;
        //重置筛选
        if($_REQUEST['resetForm']){
            unset ($_SESSION['search_data']);
            unset ($_SESSION['category_id']);
            unset ($_SESSION['video_label']);
            unset ($_SESSION['main_people']);

        }


        //搜索筛选
        if ($_REQUEST['search_data'] && !empty($_REQUEST['search_data']) &&  $_REQUEST['search_data'] != 'clear') {
            session('search_data',$_REQUEST['search_data']);
        }else if($_REQUEST['search_data'] == '' && isset($_REQUEST['search_data']) || $_REQUEST['search_data'] == 'clear'){
            unset($_SESSION['search_data']);
        }

        if (session('search_data')){
            $viewModel = D('VideoFilterView');
            $where['attr_value'] = array('like','%'.session('search_data').'%');
            $ids = $viewModel->distinct(true)->where($where)->getField('id',true);

            if(count($ids))
                $map['id|title_cn|title_en'] = array(array('in',$ids),array('like','%'.session('search_data').'%'),array('like','%'.session('search_data').'%'),'_multi'=>true);
            else
                $map['title_cn|title_en'] = array('like','%'.session('search_data').'%');
            $view = 'video-grid';
        }

        //属性筛选
        $attr_filter = array();
        //分类筛选
        if ($_REQUEST['category_id'] == 'all'){
            unset ($_SESSION['category_id']);
        }else if ($_REQUEST['category_id']){
            session('category_id',$_REQUEST['category_id']);
        }

        if (session('category_id')){
            $map['category_id'] = session('category_id');
            $view = 'video-grid';
            session('video_view','video-grid');
        }
        //标签筛选
        if ($_REQUEST['attr_id'] == 1){
            if ($_REQUEST['attr_value']){
                session('video_label',$_REQUEST['attr_value']);
            }else {
                unset ($_SESSION['video_label']);
            }
        }

        if (session('video_label')){
            $attr_filter['attr_value'] = array('like','%'.session('video_label').'%');
        }
        //主要人物筛选
        if ($_REQUEST['attr_id'] == 2){
            if ($_REQUEST['attr_value']){
                session('main_people',$_REQUEST['attr_value']);
            }else {
                unset ($_SESSION['main_people']);
            }
        }
        if (session('main_people')){
            $attr_filter['attr_value'] = array('like','%'.session('main_people').'%');
        }


        if (count($attr_filter)){
            $filter_ids = $attribute->distinct(true)->where($attr_filter)->getField('video_id',true);
            $map['id'] = array('in',$filter_ids);
            $view = 'video-grid';
            session('video_view','video-grid');
        }

        //分页处理
        $count = D(CONTROLLER_NAME)->field($field)->where($map)->order('created_at desc')->count();
        $Page = new Page($count,6);// 实例化分页类 传入总记录数和每页显示的记录数
        //$Page->setConfig()设置样式
        $Page->setConfig('prev',  '<span aria-hidden="true">上一页</span>');//上一页
        $Page->setConfig('next',  '<span aria-hidden="true">下一页</span>');//下一页
        $Page->setConfig('first', '<span aria-hidden="true">首页</span>');//第一页
        $Page->setConfig('last',  '<span aria-hidden="true">尾页</span>');//最后一页
        $Page->setConfig ( 'theme', '<li><a>%NOW_PAGE%/%TOTAL_PAGE%</a></li>  %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%' );
        $show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $data = D(CONTROLLER_NAME)->field($field)->where($map)->order('created_at desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        if($Page->nowPage > 1){
            $view = 'video-grid';
            session('video_view','video-grid');
        }

        if (count($map) > 1){
            $result_ids =  D(CONTROLLER_NAME)->where($map)->getField('id',true);
            if(count($result_ids)) $condition['video_id'] = array('in',$result_ids);
        }

        $condition['attr_id'] = 1;
        $this->assign('video_label',$attribute->distinct(true)->field('attr_value,attr_id')->where($condition)->order('attr_id desc')->limit(20)->select());
        $condition['attr_id'] = 2;
        $this->assign('main_people',$attribute->distinct(true)->field('attr_value,attr_id')->where($condition)->order('attr_id desc')->limit(20)->select());


        $this->assign('categorys',getVideoCategory());
        $this->assign('view',$view);
        $this->assign('page',$show);//赋值分页输出
        $this->assign('videolist',$data);
    }

    /**
     *  ajax 获取视频分享详情
     */
    public function viewDetail() {
        $id = $_REQUEST['id'];
        $model = D(CONTROLLER_NAME);
        $attr_model = new VideoAttrModel();
        $data = $model->getById($id);
        $data['category'] = getOptionsLabel($data['category'],C('category'));
        $data['tag'] = $attr_model->getAttrByVideoId($id,1);
        $data['people'] = $attr_model->getAttrByVideoId($id,2);
        echo json_encode($data);
    }

    /**
     *  通过邮件形式 发送视频
     */
    public function shareVideoByEmail(){
        $email = $_REQUEST['email'];
        $share_link = $_REQUEST['share_link'];
        if (!$email) {
            $this->error('请输入发送人邮箱！','',true);
        }
        if (!$_REQUEST['share_title']) {
            $this->error('请输入分享视频标题！','',true);
        }
        if (!$share_link) {
            $this->error('发送失败，请输入分享视频地址！','',true);
        }
        $model = D('ShareList');
        $data['share_link'] = $share_link;
        $data['var_key'] = md5(time().$_REQUEST['video_id']);
        $data['title'] = $_REQUEST['share_title'];
        $data['shareder'] = getUserName();
        if ($_REQUEST['share_password']){
            $data['share_password'] = $_REQUEST['share_password'];
        }
        $data['created_at'] = time();

        if ($model->add($data) === false){
            $this->success('发送失败 '.$model->getLastSql(),'',true);
        }

        $content = explode('.',U('Public/shareVideo',array('key' => $data['var_key'])));
        $body = $_REQUEST['message'].'<br/>链接如下：'.C('DO_MAIN').$content[0];
        if ( $data['share_password']){
            $body .= '<br/>提取码:'.$data['share_password'];
        }
        if(sendEmail($email,'',$_REQUEST['share_title'],$body,null)){
            $this->success('发送成功！','',true);
        } else {
            $this->success('发送失败 ','',true);
        }
    }


    function update() {

        $model = D ( CONTROLLER_NAME );
        $attr_model = new VideoAttrModel();

        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        if (!empty($_FILES['video_thumbnail']['name'])) {
            //上传新头像
            $model->video_thumbnail =  $this->uploadImage(getVideoPath($model->id));
            //删除以前的头像
            $oldfile = $_SERVER['DOCUMENT_ROOT'].D( CONTROLLER_NAME )->where('id='.$model->id)->getField('video_thumbnail');
            if( file_exists($oldfile) && is_file( $oldfile ) )
            {
                unlink( $oldfile );
            }
        }

        // 更新数据
        $list=$model->save ();
        if (false !== $list) {
            session('video_view','video-list');
            //成功提示
            $this->success ('编辑成功!');
        } else {
            //错误提示
            $this->error ('编辑失败!');
        }
    }

    function insert() {

        $model = D (CONTROLLER_NAME);
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        $id = M('video')->max('id')+1;
        $model->id = $id;
        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
            if (!empty($_FILES['video_thumbnail']['name'])) {
                //上传新头像
                $data['video_thumbnail'] =  $this->uploadImage(getVideoPath($id));
                D (CONTROLLER_NAME)->where('id='.$id)->save($data);
            }
            session('video_view','video-list');
            $this->success ('新增成功!');
        } else {
            //失败提示
            $this->error ('新增失败!');
        }
    }

    /**
     *  多选删除
     */
    public function multiDelete() {
        $model = M (CONTROLLER_NAME);
        if (! empty ( $model )) {
            $pk = $model->getPk ();
            $ids = $_REQUEST ['ids'];
            if (isset ( $ids )) {
                $condition = array ($pk => array ('in', explode ( ',', $ids ) ) );
                $list=$model->where ( $condition )->delete();
                session('video_view','video-list');
                if ($list!==false) {
                    $map = array ('video_id' => array ('in', explode ( ',', $ids ) ) );
                    if( D('video_attr')->where ( $map )->delete() === false){
                        $this->error ('删除失败！属性删除失败','',true);
                    }
                    $this->success ('删除成功！','',true );
                } else {
                    $this->error ('删除失败！','',true);
                }
            } else {
                $this->error ( '非法操作','',true );
            }
        }
    }

    /**
     * autocomplete 模糊查询
     */
    public function ajaxGetAttribute() {
        $query =  $_REQUEST['query'];
        $map['attr_value'] = array('like','%'.trim($_REQUEST['query']).'%');
        $data = M('video_attr')->distinct(true)->where($map)->getField('attr_value',true);
        echo json_encode($data);
    }

    /**
     * ajax 添加标签
     */
    public function ajaxPushLabel() {
        $attr_model = new VideoAttrModel();
        if ($_REQUEST['video_id'] == '') {
            $id = M('video')->max('id');
            $video_id = $id+1;
        } else {
            $video_id =   $_REQUEST['video_id'] ;
        }

        if ($attr_model->delAttr($video_id,$_REQUEST['attr_id']) === false){
            $this->error('标签添加失败！');
        }
        if ($_REQUEST['tags'] && $attr_model->addAttr($_REQUEST['tags'],$video_id,$_REQUEST['attr_id']) === false){
            $this->error('标签添加失败！');
        }
        echo 'success';
    }

    /**
     * 获取分享视频的链接
     */
    public function getShareVideoLink() {
        $model = D('ShareList');
        $data['share_link'] = $_REQUEST['share_link'];
        $data['var_key'] = md5(time());
        $data['title'] = $_REQUEST['share_title'];
        $data['shareder'] = getUserName();
        if ($_REQUEST['share_password']){
            $data['share_password'] = $_REQUEST['share_password'];
        }
        $data['created_at'] = time();

        if ($model->add($data) === false){
            $this->success('生成失败 '.$model->getLastSql(),'',true);
        }
        //'http://'.$_SERVER['SERVER_NAME'].
        echo U('Public/shareVideo',array('key' => $data['var_key']),true,true);
    }




}
?>